﻿$(function () {
    $("#sidebar-container").jstree({
        "core": { "initially_open": ["tree-root"] },
        "themes": {
            "dots": false,
            "icons": false
        },
        "plugins": ["themes", "html_data"]
    }).bind("open_node.jstree", onOpenNode);

    var ctgid = getCookie("branch-category");
    $("#BranchCategory").val(ctgid);
    onBranchCategoryStatusChanged();
})

function onBranchCategoryStatusChanged() {
    var obj = $("#branch-select-prompt");
    var directory = $("#branch-directory-detail");
    var value = $("#BranchCategory").val();
    if (value > 0) {
        var url = GetUrl("GetCategoryDirectory", "Home");
        $.post(url, { id: value }, function (data) {
            obj.parent().hide();
            $("#parent-branch-name").text(data.parent);
            $("#child-branch-name").text(data.child);
            directory.removeClass("hidden");
            setCookie("branch-category", value);
        });
    } else {
        obj.parent().show();
    }
}

function onOpenNode(e, data) {
    var obj = $(data.args[0]);
    if (obj.attr("status") == "unloaded") {
        setTimeout(function () { getBranches(obj, loadBranchLeafSuccess); }, 500);
    }
}

function loadBranchLeafSuccess(obj, data) {
    if (data.length <= 0) return;

    var nodes = "";
    for (var i in data) {
        nodes += "<li class='jstree-leaf' cid='" + data[i].Category_ID + "' cname='" + data[i].Category_Name + "'><ins class='jstree-icon'>&nbsp;</ins><a href='javascript:void(0);' onclick='selectBranch(this)'>" + data[i].Category_Name + "</a></li>";
    }
    $(obj).find("ul").html(nodes);
    $(obj).attr("status", "loaded");
}

function selectBranch(obj) {
    var cid = $(obj).parent().attr("cid");
    var original = $("#BranchCategory").val();
    if (cid != original) {
        setBranch(cid)
    }
}

function setBranch(id) {
    $("#BranchCategory").val(id);
    onBranchCategoryStatusChanged();
}

function getBranches(obj, action) {
    var id = obj.attr("cid");
    var url = GetUrl("GetCategoryBranches", "Home");
    $.post(url, { id: id }, function (data) {
        action(obj, data);
    });
}